
<template>
  <div>
    <!-- 面包导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="#">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>商品分类 </el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格 -->
      <tree-table
        class="treetable"
        :data="catelist"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-circle-check"
            style="color: lightgreen"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i class="el-icon-circle-close" style="color: red" v-else></i>
        </template>
        <!-- 级别 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" v-if="scope.row.cat_level === 1" type="success"
            >二级</el-tag
          >
          <el-tag size="mini" v-if="scope.row.cat_level === 2" type="warning"
            >三级</el-tag
          >
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showChangeCateDialog(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCateItem(scope.row)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加分类对话框 -->
      <el-dialog
        title="添加分类"
        @close="closeaddCateDialog"
        :visible.sync="addCateDialogFlag"
        width="50%"
      >
        <el-form
          :model="addCateDate"
          :rules="addCateDaterules"
          ref="addCateDateref"
          label-width="100px"
        >
          <el-form-item label="分类名称：" prop="cat_name">
            <el-input v-model="addCateDate.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级名称：">
            <el-cascader
              :clearable="true"
              v-model="cascaderselectkey"
              :options="parentCateList"
              :props="cascaderprops"
              @change="cascaderChange"
              clearCheckedNodes
              :checkStrictly="true"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCateDialogFlag = false">取 消</el-button>
          <el-button type="primary" @click="addCateButton">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
  title="修改分类"
  :visible.sync="showChangeCateFlag"
  width="50%"
  @close='closeChangeCateDialog'
  >
<el-form
          :model="changeCateDate"
          :rules="changeCateDateRules"
          ref="changeCateDateref"
          label-width="100px"
        >
          <el-form-item label="分类名称：" prop="cat_id">
            <el-input v-model="changeCateDate.cat_name"></el-input>
          </el-form-item>
</el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="showChangeCateFlag = false">取 消</el-button>
    <el-button type="primary" @click="changeCateItem">确 定</el-button>
  </span>
</el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //查询要带的信息
      querInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品列表
      catelist: [],
      //总数据条数
      total: 0,
      //列属性
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          template: "opt",
        },
      ],
      //添加分类对话框flag
      addCateDialogFlag: false,
      //添加分类 时候的信息
      addCateDate: {
        //添加的分类的名称
        cat_name: "",
        //父级分类的id
        cat_pid: 0,
        //当前分类等级
        cat_level: 0,
      },
      //添加分类 table规则
      addCateDaterules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      //父级商品分类（1，2级别）的数组
      parentCateList: [],
      //cascader的属性  左边option是数据源 prop是子
      //节点和父节点的关系（从数据源你们找这些关系
      // v-model是要展示的数据  通过change事件从数据源获得数据
      //赋值给v-model绑定的数组（目的是不改变数据源）
      cascaderprops: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true,
      },
      //v-model绑定的选中的数据
      cascaderselectkey: [],

      //修改分类对话框 flag
      showChangeCateFlag:false,
      //修改分类的formdate
      changeCateDate:{
        cat_id:0,
        cat_name:'',
      },
      //修改分类的规则
      changeCateDateRules:{
        cat_id:[
           { required: true, message: '请输入活动名称', trigger: 'blur' },
        ]
      }


    };
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.querInfo,
      });
      //   console.log(res);
      if (res.meta.status !== 200)
        return this.$message.errro("获取商品列表失败");
      this.catelist = res.data.result;
      this.total = res.data.total;
    },

    //监听pagesize事件变化
    handleSizeChange(newsize) {
      this.querInfo.pagesize = newsize;
      this.getCateList();
    },
    //监听pagenum
    handleCurrentChange(newpagenum) {
      this.querInfo.pagenum = newpagenum;
      this.getCateList();
    },

    //打开添加分类对话框
    showAddCateDialog() {
      this.getParentCateList();
      this.addCateDialogFlag = true;
    },
    //获取父级分类列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品列表失败");
      this.parentCateList = res.data;
    },
    //选择的选项改变时候改变选中的 v-mode值
    cascaderChange() {
      if (this.cascaderselectkey.length > 0) {
        //父级id
        this.addCateDate.cat_pid = this.cascaderselectkey[
          this.cascaderselectkey.length - 1
        ];
        //分类等级
        this.addCateDate.cat_level = this.cascaderselectkey.length;
        return;
      } else {
        this.addCateDate.cat_pid = 0;
        this.addCateDate.cat_level = 0;
      }
    },
    //点击确定 添加新的分类
    async addCateButton() {
      const { data: res } = await this.$http.post(
        "categories",
        this.addCateDate
      );
      // console.log(res);
      if (res.meta.status !== 201) return this.$message.errro("添加分类失败");
      this.$message.success("添加分类成功");
      this.getCateList();

      this.addCateDialogFlag = false;
      this.cascaderselectkey = [];
      this.addCateDate.cat_pid = 0;
      this.addCateDate.cat_level = 0;
    },
    //关闭对话框
    closeaddCateDialog() {
      this.$refs.addCateDateref.resetFields();
      this.cascaderselectkey = [];
      this.addCateDate.cat_pid = 0;
      this.addCateDate.cat_level = 0;
    },

    //删除当前分类
    async deleteCateItem(info) {
      const {data:res}  =await this.$http.delete(`categories/${info.cat_id}`)
      if(res.meta.status!==200)return this.$message.errror('删除失败')
      this.$message.success('删除成功')
      this.getCateList()
    },

    //点击修改打开修改界面
    async showChangeCateDialog(info){

      const {data:res} = await this.$http.get('categories/'+info.cat_id)
      console.log(res);
      this.changeCateDate.cat_id=res.data.cat_id
      this.changeCateDate.cat_name=res.data.cat_name
      
      this.showChangeCateFlag = true

    },
    //点击修改确认
    async changeCateItem(){
      const {data:res} = await this.$http.put('categories/'+this.changeCateDate.cat_id,
      {cat_name:this.changeCateDate.cat_name})
      if(res.meta.status!==200)return this.$message.error('修改失败')
      this.getCateList()
      this.showChangeCateFlag = false
    },
    //关闭修改对话框
    closeChangeCateDialog(){
      this.changeCateDate.cat_id = 0
      this.changeCateDate.cat_name=''
    }
  },
  created() {
    this.getCateList();
  },
};
</script>

<style lang="less" scoped>
.treetable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
  // overflow: hidden;
}

.el-cascader-panel {
  height: 300px;
}
</style>